const tableEle = document.querySelector('table')
let inputAll = document.querySelector('.cart-wraper .all-choise')   //找到全选按钮框框
/**
 * 显示购物车列表
 */
function showCartList() {
    let cartList = localStorage.getItem('CART-LIST') || '[]'
    let singleChoice = document.getElementsByName('singleChoice')
    cartList = JSON.parse(cartList) // 购物车数组
    // //初始化全选 
    inputAll.checked=cartList.every(item=>{
        return item.state==true
    })
    
    let str = `<tr>
                    <th>&nbsp;&nbsp;&nbsp;</th>
                    <th>序号</th>
                    <th>图片</th>
                    <th>名称</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th width="100px">总价</th>
                    <th>操作</th>
                </tr>`

    let arr = cartList.map(item => {
        // checked='${item.state}'
        return `<tr>
                       <td><input type='checkbox'   name='singleChoice' data-id='${item.id}'></td>
                        <td>${item.id}</td>
                        <td><img src="${item.url}" alt="pic1"/></td>
                        <td class="name">${item.name}</td>
                        <td>${item.price}</td>

                        <td>
                          <input type="button" value="-" name="minus"${item.num == 0 ? 'disabled' : ''}data-id="${item.id}"/>
                           <input type="text" value="${item.num}" name="amount"/>
                           <input type="button" value="+"  name="plus"  data-id="${item.id}" />
                        </td>

                        <td>${(item.num * item.price).toFixed(2)}</td>
                        <td>移入收藏<br/>
                            <span class="del" data-id="${item.id}">删除</span>
                        </td>
                    </tr>`
    })
    tableEle.innerHTML = str + arr.join('')
//初始化单选
    singleChoice.forEach(item=>{
        cartList.forEach(citem=>{
            if(item.dataset.id==citem.id){
                item.checked=citem.state
            }
        })
    })

//初始化总价
    let sum=0
    let totalPriceEle = document.querySelector(".total")
    cartList.forEach(item=>{
        if(item.state==true){
            sum=sum+item.num*item.price
        }
    })
    totalPriceEle.innerHTML='最后结算总价：' + sum.toFixed(2)
}

// 购物车数量自增1,本地存储
// 委托事件
function bindProduct() {
    tableEle.addEventListener('click', function (e) {  //找到表格对其添加监听事件
        e == e || window.event    //事件对象
        let target = e.target || e.srclement   //目标对象
        e.stopPropagation()
        //现实商品数量加1
        if (target.getAttribute('name') == 'plus') {    //根据name判断找到的加号
            let listStr = localStorage.getItem('CART-LIST') || '[]'  //在本地获取已经存储的数据，返回listStr
            let cartList = JSON.parse(listStr)  //list为对象  
            let id = target.dataset.id
            console.log(id)

            cartList.forEach(item => {
                if (id == item.id) {
                    item.num++
                }
            });
            
            localStorage.setItem('CART-LIST', JSON.stringify(cartList))
            showCartList()
            
        }

        //数量减去1
        if (target.getAttribute('name') == 'minus') {  //根据name找到减号
            let listStr = localStorage.getItem('CART-LIST') || '[]'
            let cartList = JSON.parse(listStr)
            let id = target.dataset.id
            let Product = cartList.find(item => item.id == id)
            Product.num--
            //加入本地存储
            localStorage.setItem('CART-LIST', JSON.stringify(cartList))
            showCartList()
            

        }
        //  删除数据
        if (target.getAttribute('class') == 'del') {
            let listStr = localStorage.getItem('CART-LIST') || '[]'
            let cartList = JSON.parse(listStr)
            let id = target.dataset.id

            let index = cartList.findIndex(function (item) {
                return item.id == id
            })
            cartList.splice(index, 1)
            localStorage.setItem('CART-LIST', JSON.stringify(cartList))
            showCartList()
        }

        // 选项框
        
        if (target.getAttribute('name') == 'singleChoice') {//getAttribute对事件目标对象的name进行判断其是否为单选框
            let listStr = localStorage.getItem('CART-LIST') || '[]'
            let cartList = JSON.parse(listStr)
            let id = target.dataset.id     //datast获取target的自定义属性id赋值给id
            cartList.forEach(item => {
                if (item.id == id) {
                    item.state = !item.state
                }
            })
            localStorage.setItem('CART-LIST', JSON.stringify(cartList))

            inputAll.checked = cartList.every(item => {
                return item.state == true
            })
            showCartList()
        }
        
    })

    

}



// 找到全选框框，找到每行数据的复选框
    inputAll.addEventListener('click', function (e) {
        let singleChoice = document.getElementsByName('singleChoice')
        let listStr = localStorage.getItem('CART-LIST') || '[]'
        let cartList = JSON.parse(listStr)
        cartList.forEach(item => {
            item.state = !item.state
        })
        
        
        inputAll.checked = cartList.every(item => {
            return item.state == true
        })
        singleChoice.forEach(item => {
            item.checked = inputAll.checked
        })
        localStorage.setItem('CART-LIST', JSON.stringify(cartList))
        showCartList()
    })




showCartList()
bindProduct()